from fastapi import FastAPI, HTTPException, Request
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse, HTMLResponse
from fastapi.templating import Jinja2Templates
from pydantic import BaseModel
from typing import Optional, List, Dict, Any
from database_analyzer import DatabaseAnalyzer
from models import DatabaseConnection, DatabaseType, TableInfo, Relationship
import uvicorn
import os

app = FastAPI(title="数据库ER图生成工具", description="连接数据库并生成表结构关系图")

# 创建静态文件和模板目录
os.makedirs("static", exist_ok=True)
os.makedirs("templates", exist_ok=True)

app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")

@app.get("/", response_class=HTMLResponse)
async def home(request: Request):
    return templates.TemplateResponse("index.html", {"request": request})

@app.get("/test", response_class=HTMLResponse)
async def test_frontend(request: Request):
    return templates.TemplateResponse("test_frontend.html", {"request": request})

@app.get("/js_test")
async def js_test(request: Request):
    return templates.TemplateResponse("test_js.html", {"request": request})

class AnalyzeRequest(BaseModel):
    db_type: str
    host: Optional[str] = None
    port: Optional[int] = None
    database: str
    username: Optional[str] = None
    password: Optional[str] = None
    tables: Optional[List[str]] = None  # 要包含的表名列表，如果为null则包含所有表

@app.post("/analyze")
async def analyze_database(request: AnalyzeRequest):
    try:
        print(f"收到分析请求: {request.db_type}, database: {request.database}")
        print(f"请求数据: {request}")
        if request.tables:
            print(f"筛选表: {request.tables}")
        else:
            print("未指定筛选表，将返回所有表")
        
        # 构建数据库连接对象
        connection = DatabaseConnection(
            db_type=request.db_type,
            host=request.host,
            port=request.port,
            database=request.database,
            username=request.username,
            password=request.password
        )
        
        analyzer = DatabaseAnalyzer(connection)
        tables = analyzer.get_tables()
        relationships = analyzer.get_relationships()
        
        # 如果指定了筛选表，则进行筛选
        if request.tables:
            print(f"进行表筛选，原始表数量: {len(tables)}")
            # 筛选表
            filtered_tables = [table for table in tables if table.name in request.tables]
            print(f"筛选后表数量: {len(filtered_tables)}")
            print(f"筛选的表名: {[table.name for table in filtered_tables]}")
            
            # 筛选关系（只保留两个表都在筛选列表中的关系）
            filtered_relationships = [
                rel for rel in relationships 
                if rel.from_table in request.tables and rel.to_table in request.tables
            ]
            print(f"筛选后关系数量: {len(filtered_relationships)}")
            
            tables = filtered_tables
            relationships = filtered_relationships
        
        print(f"分析完成: {len(tables)} 个表, {len(relationships)} 个关系")
        
        result = {
            "success": True,
            "tables": tables,
            "relationships": relationships
        }
        
        print(f"返回数据大小: {len(str(result))} 字符")
        return result
        
    except Exception as e:
        print(f"分析失败: {str(e)}")
        import traceback
        traceback.print_exc()
        raise HTTPException(status_code=500, detail=str(e))

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)